<?php

/*
 * This file will perform the ajax for adding the transactions of attachment.
 * This file will used for the transactions regarding the attachment when the user is in its view page.
 * 
 * Created by: Peter Agno Jr.
 * Date created: Octber 23, 2011
 * 
 * In parameters: documentId, position, fromMainDoc (a flag that determines if the ones accessing this file is from a main document or from an attachment.) 
 * Out parameters: Show Send Attachment Screenlet, Archive Button, and/or Acknowledge Sent Attachment Screenlet
 */
session_start();

// Start - Checker for those users who will just go to the page by typing directly in the url.
if ($_POST) {   
    include('../includes/siteConfig.php'); 

    // connect to database
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');

    $documentId = $_POST['documentId'];
    $scrnPostn = $_POST['scrnPostn'];
    $fromMainDoc = $_POST['fromMainDoc'];
    $attchTransInfo = "";
    
    //********************************************************************************************************
    /*
     * Define the functions in here
     */
    
    // Start function - Display Archive button
    function dispArchiveBtn($btnFlag, $attchTransInfo, $scrnPostn) {
        $attchTransInfo = $attchTransInfo . "<div id='archiveBtnAttchDiv_".$scrnPostn."' class='archiveBtnAttch'>";
        $attchTransInfo = $attchTransInfo . "<span class='archiveBtnAttch_".$scrnPostn."'";
         
        if ( $btnFlag == "hide" )
         $attchTransInfo = $attchTransInfo . "style='display:none;'";

        $attchTransInfo = $attchTransInfo . "><input type='button' name='archiveBtn_".$scrnPostn."' id='archiveBtn_".$scrnPostn."' class='siteGreenButton archiveBtn' value='Archive' /></span> &nbsp </div>";
        return $attchTransInfo;
    } // End function - Display Archive button
    
    // Start function - Display Send Attachment Screenlet
    function sendAttachScrn($scrnFlag, $attchTransInfo, $scrnPostn) {
        
        $attchTransInfo = $attchTransInfo . "<div id='sendAttachScrn_".$scrnPostn."'";

        if ( $scrnFlag == "hide" )
            $attchTransInfo = $attchTransInfo . "style='display:none;'";

        $attchTransInfo = $attchTransInfo . ">";
        $attchTransInfo = $attchTransInfo . 
            "
                <span class='screenlet'>Send Attachment</span>
                <table>
                    <tr>
                        <td>Receiver Type</td>
                        <td>
                            <select name='receiverType_".$scrnPostn."' id='receiverType_".$scrnPostn."' class='receiverType'>     
                                <option value='Internal'>Within the Organization</option>
                                <option value='External'>Others</option>
                            </select>
                        </td>
                    </tr>
                    <tr class='deptRow_".$scrnPostn."'>
                        <td>Department</td>
                        <td>
                            <select name='deptDrpDwn_".$scrnPostn."' id='deptDrpDwn_".$scrnPostn."' class='deptDrpDwn'>
            ";

            $deptQuery =
                "
                    SELECT departmentId, departmentName
                    FROM Department
                    ORDER BY departmentName
                ";

            $deptResult = mysql_query($deptQuery) or die ('Error in query: $deptQuery. ' . mysql_error());

            while ( $deptRow = mysql_fetch_array($deptResult) )
                $attchTransInfo = $attchTransInfo . "<option value='".$deptRow['departmentId']."'>".$deptRow['departmentName']."</option>";

            mysql_free_result($deptResult);


            $attchTransInfo = $attchTransInfo . 
                "
                                    </select>
                                </td>
                            </tr>
                            <tr class='posRow_".$scrnPostn."'>
                                <td>Position</td>
                                <td>
                                    <select name='posDrpDwn_".$scrnPostn."' id='posDrpDwn_".$scrnPostn."'>
                                    </select>
                                </td>
                            </tr>
                            <tr class='othersRow_".$scrnPostn."' style='display:none;'>
                                <td>Send to : </td>
                                <td>
                                    <input type='text' class='sendToIptBx' name='sendToIptBx_".$scrnPostn."' id='sendToIptBx_".$scrnPostn."' value='' size='22' maxlength='40'/>

                                    <!-- Used for the search engine of external accounts -->
                                    <table style='border-top : 0px; display:none; background-color: #c6e89f;' class='tableExAcc tableExAcc_".$scrnPostn."' id='tableExAcc_".$scrnPostn."'>
                                    </table>
                                </td>
                            </tr>
                            <tr>
                                <td></td>
                                <td><input type='button' name='sendToBtn_".$scrnPostn."' id='sendToBtn_".$scrnPostn."' class='sendToBtn siteGreenButton' value='Send' /></td>
                            </tr>
                        </table>
                    </div>
                ";
                  
        return $attchTransInfo;
    } // End function - Display Send Attachment Screenlet
    
    // Start function - Display Acknowledge Sent Attachment Screenlet
    function ackSentAttachScrn($attachmentId, $scrnFlag, $attchTransInfo, $scrnPostn) {
        $attchTransInfo = $attchTransInfo . "<div id='ackSentAttachScrn_".$scrnPostn."'";
        
        if ( $scrnFlag == "hide" )
            $attchTransInfo = $attchTransInfo . "style='display:none;'";
        
        $attchTransInfo = $attchTransInfo . 
            "
                >
                    <span class='screenlet'>Acknowledge</span>
                    <table>
                        <tr>
                            <td>
            ";

            // Get the external receiver name of the attachment
            $query = 
                "
                    SELECT EA.exAccName as exAccName
                    FROM Sent_Attachment as SA, ExternalAccount as EA
                    WHERE SA.documentId = '$attachmentId' AND SA.orgFlag = 'External' AND SA.receiveFlag = 'Pending'
                        AND SA.receiverId = EA.exAccId
                ";

            $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
            $row = mysql_fetch_array($result);
            
            $attchTransInfo = $attchTransInfo . 
                "
                                    Did <span id='rcvrNameSpan_".$scrnPostn."'>".$row['exAccName']."</span> receive the attachment?
                                </td>
                            </tr>
                            <tr>
                                <td align='center'><input type='button' name='ackSentBtn_".$scrnPostn."' id='ackSentBtn_".$scrnPostn."' class='siteGreenButton ackSentBtn' value='Yes' /></td>
                            </tr>
                        </table>
                    </div>
                ";
        
        return $attchTransInfo;
    } // End function - Display Acknowledge Sent Attachment Screenlet
    
    // Start - check if the attachment has main document
    function hasMainDoc($attachmentId){
        $query = 
            "
                SELECT *
                FROM Attachment
                WHERE attachmentId = '$attachmentId'
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        
        if ( $row['mainDocumentId'] == null )
            return false;
        else
            return true;
    } // End - check if the attachment has main document
    
    // Start function - Check if the document is attached to a main document
    function isAttached($attachmentId) {
        if ( hasMainDoc($attachmentId) == true ) {
            // Check if the current log is detached
            $query = 
                "
                    SELECT *
                    FROM Log
                    WHERE documentId = '$attachmentId'
                    ORDER BY logId DESC
                ";
            
            $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
            $row = mysql_fetch_array($result);
            
            if ( $row['activity'] == 'Detached' ) {
                error_log('cc');
                return false;
            }
            else {
                // Check if it is in Sent_Attachment
                $query = 
                    "
                        SELECT *
                        FROM Sent_Attachment
                        WHERE documentId = '$attachmentId'
                    ";

                $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
                
                if ( mysql_num_rows($result) == 0 ) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        else {
            return false;
        }
    } // End function - Check if the document is attached to a main document
    
    // Start function - Check if the logged user is the current holder of the attachment
    function logUserIsHolder($attachmentId, $userId) {
        $query = 
            "
                SELECT location
                FROM Attachment
                WHERE attachmentId = '$attachmentId'
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        
        if ( $row['location'] == $userId )
            return true;
        else
            return false;
    } // End function - Check if the logged user is the current holder of the attachment
    
    // Start function - Check if the document was sent externally
    function wasSentExt($attachmentId) {
        $query = 
            "
                SELECT *
                FROM Sent_Attachment as SA
                WHERE SA.documentId = '$attachmentId' AND SA.orgFlag = 'External' AND SA.receiveFlag = 'Pending'
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        
        if ( mysql_num_rows($result) > 0 )
            return true;
        else
            return false;
    } // End function - Check if the document was sent externally
    
    // Start function - Check if not yet received externally 
    function notYetReceivedExt($attachmentId) {
        $query = 
            "
                SELECT *
                FROM Sent_Attachment
                WHERE documentId = '$attachmentId' AND orgFlag = 'External' AND receiveFlag = 'Pending'
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
         
        if ( mysql_num_rows($result) > 0 )
            return true;
        else
            return false;
    } // End function - Check if not yet received externally 
    
    // Start function - Check if the logged user is the one who sent
    function checkUserSentAttach($attachmentId, $userId) {
        $query = 
            "
                SELECT *
                FROM Sent_Attachment
                WHERE documentId = '$attachmentId' AND senderId = '$userId' AND receiveFlag = 'Pending'
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
         
        if ( mysql_num_rows($result) > 0 )
            return true;
        else
            return false;
    } // End function - Check if the logged user is the one who sent
    
    // Start function - Check if the attachment was received
    function isReceived($attachmentId) {
        $query = 
            "
                SELECT *
                FROM Sent_Attachment
                WHERE documentId = '$attachmentId' AND receiveFlag = 'Pending'
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
         
        if ( mysql_num_rows($result) > 0 )
            return false;
        else
            return true;
    } // End function - Check if the attachment was received
    
    // Start function - Check if the location of the attachment is the current logged user
    function isHolder($attachmentId, $userId) {
        $query = 
            "
                SELECT *
                FROM Attachment
                WHERE attachmentId = '$attachmentId' AND location = '$userId'
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
         
        if ( mysql_num_rows($result) > 0 )
            return true;
        else
            return false;
    } // End function - Check if the location of the attachment is the current logged user
    
    // Start function - Check if the attachment was archived by the logged user
    function isArchived($attachmentId, $userId) {
        $query = 
            "
                SELECT userId, activity
                FROM Log
                WHERE documentId = '$attachmentId'
                ORDER BY logId DESC
            ";
        
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        
        if ( $row['userId'] == $userId && $row['activity'] == 'Archived' )
            return true;
        else
            return false;
    } // End function - Check if the attachment was archived by the logged user
    
    //********************************************************************************************************
    
    // *****************************************************************************
    // Start - the whole code for attachment transactions

        // If the document is attached to a main document, then perform the steps
        if ( isAttached($documentId) == true ) {
            error_log("....1");
            // Check if the logged user is the current holder of the attachment
            if ( (logUserIsHolder($documentId, $_SESSION['loggedUserId']) == true) && ($fromMainDoc == "true") ) {
                error_log("....2");
                $attchTransInfo = dispArchiveBtn("hide", $attchTransInfo, $scrnPostn); // Display Archive button
                $attchTransInfo = sendAttachScrn("show", $attchTransInfo, $scrnPostn);   // Display Send Attachment Screenlet
                $attchTransInfo = ackSentAttachScrn($documentId, "hide", $attchTransInfo, $scrnPostn); // Display Acknowledge Sent Attachment Screenlet
            }
            else {
                error_log("....3");
                // Perform the display of archive button function, but hide it. 
                // It will be used to see the appended close button.
                $attchTransInfo = dispArchiveBtn("hide", $attchTransInfo, $scrnPostn); // Display Archive button
                $attchTransInfo = sendAttachScrn("hide", $attchTransInfo, $scrnPostn);   // Display Send Attachment Screenlet
                $attchTransInfo = ackSentAttachScrn($documentId, "hide", $attchTransInfo, $scrnPostn); // Display Acknowledge Sent Attachment Screenlet
            }
        }
        else {
            error_log("....4");
            // If attachment was sent externally, then perform the steps
            if ( wasSentExt($documentId) == true ) {
                error_log("....5");
                // Check if not yet received externally
                if ( notYetReceivedExt($documentId) == true ) {
                    error_log("....6");
                    // Check if the logged user is the one who sent
                    if ( checkUserSentAttach($documentId, $_SESSION['loggedUserId']) == true ) {
//                        error_log("....7");
                        $attchTransInfo = dispArchiveBtn("hide", $attchTransInfo, $scrnPostn); // Display Archive button
                        $attchTransInfo = sendAttachScrn("hide", $attchTransInfo, $scrnPostn);   // Display Send Attachment Screenlet
                        $attchTransInfo = ackSentAttachScrn($documentId, "show", $attchTransInfo, $scrnPostn); // Display Acknowledge Sent Attachment Screenlet
                    }
                    else {
                        error_log("....8");
                        // Perform the display of archive button function, but hide it. 
                        // It will be used to see the appended close button.
                        $attchTransInfo = dispArchiveBtn("hide", $attchTransInfo, $scrnPostn); // Display Archive button
                        $attchTransInfo = sendAttachScrn("hide", $attchTransInfo, $scrnPostn);   // Display Send Attachment Screenlet
                        $attchTransInfo = ackSentAttachScrn($documentId, "hide", $attchTransInfo, $scrnPostn); // Display Acknowledge Sent Attachment Screenlet
                    }
                }
                else {
                    error_log("....9");
                    // Perform the display of archive button function, but hide it. 
                    // It will be used to see the appended close button.
                    $attchTransInfo = dispArchiveBtn("hide", $attchTransInfo, $scrnPostn); // Display Archive button
                    $attchTransInfo = sendAttachScrn("hide", $attchTransInfo, $scrnPostn);   // Display Send Attachment Screenlet
                    $attchTransInfo = ackSentAttachScrn($documentId, "hide", $attchTransInfo, $scrnPostn); // Display Acknowledge Sent Attachment Screenlet
                }
            }
            else {
                error_log("....10");
                // Check if the attachment was received, and if the location of the attachment is the current logged user
                if ( isReceived($documentId) == true && isHolder($documentId, $_SESSION['loggedUserId']) == true ) {
                    error_log("....11");
                    // Check if the attachment was archived by the logged user
                    if ( isArchived($documentId, $_SESSION['loggedUserId']) == true ) {
                        error_log("....12");
                        $attchTransInfo = dispArchiveBtn("hide", $attchTransInfo, $scrnPostn); // Display Archive button
                        $attchTransInfo = sendAttachScrn("hide", $attchTransInfo, $scrnPostn);   // Display Send Attachment Screenlet
                        $attchTransInfo = ackSentAttachScrn($documentId, "hide", $attchTransInfo, $scrnPostn); // Display Acknowledge Sent Attachment Screenlet
                    }
                    else {
                        error_log("....13");
                        $attchTransInfo = dispArchiveBtn("show", $attchTransInfo, $scrnPostn); // Display Archive button
                        $attchTransInfo = sendAttachScrn("show", $attchTransInfo, $scrnPostn);   // Display Send Attachment Screenlet
                        $attchTransInfo = ackSentAttachScrn($documentId, "hide", $attchTransInfo, $scrnPostn); // Display Acknowledge Sent Attachment Screenlet
                    }
                }
                else {
                    error_log("....16");
//                    if ( isAttached($documentId) == false && isHolder($documentId, $_SESSION['loggedUserId']) == true ) {
//                        error_log("....17");
//                        $attchTransInfo = dispArchiveBtn("show", $attchTransInfo, $scrnPostn); // Display Archive button
//                        $attchTransInfo = sendAttachScrn("show", $attchTransInfo, $scrnPostn);   // Display Send Attachment Screenlet
//                        $attchTransInfo = ackSentAttachScrn($documentId, "hide", $attchTransInfo, $scrnPostn); // Display Acknowledge Sent Attachment Screenlet
//                    }
//                    else {
//                        error_log("....18");
                        // Perform the display of archive button function, but hide it. 
                        // It will be used to see the appended close button.
                        $attchTransInfo = dispArchiveBtn("hide", $attchTransInfo, $scrnPostn); // Display Archive button
                        $attchTransInfo = sendAttachScrn("hide", $attchTransInfo, $scrnPostn);   // Display Send Attachment Screenlet
                        $attchTransInfo = ackSentAttachScrn($documentId, "hide", $attchTransInfo, $scrnPostn); // Display Acknowledge Sent Attachment Screenlet
//                    }
                }
            }
        }

    // End - the whole code for attachment transactions
    // *****************************************************************************
    
    $feed['attchTransInfo'] = $attchTransInfo;    
    echo json_encode($feed);
    
    // free result and close database
//    mysql_free_result($result);
    mysql_close($connect);
}   // End - Checker for those users who will just go to the page by typing directly in the url.
else {
 echo "You are not authorized to view this page. This incident will be reported immediately.";
}
?>
